package com.lmx.log;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;

import com.lmx.common.context.ActionContextHolder;
import com.lmx.common.util.CommonUtil;
import com.lmx.persistence.service.CommonService;
import com.lmx.repoDomain.tmodel.ReqLog;

/**
 * 
 * 
 * @author huibati
 * @version 1.00
 */
@Service
@Scope("prototype")
public class LogService<T> {

	private Log logger = LogFactory.getLog(this.getClass());

	@Autowired
	private CommonService commonService;

	public void serviceExecute() {
		// 开启线程，执行操作
		ExecutorService poolMsg = Executors.newFixedThreadPool(4);// 消息发送进程
		for (int i = 0; i < 4; i++) {
			poolMsg.execute(new WriteLog(ActionContextHolder.getLogQueue(), i+""));
		}

	}

	private class WriteLog implements Runnable {
		private LogQueue queue;

		private String remark;

		// 该构造函数初始化同步队列类变量
		public WriteLog(LogQueue queue, String remark) {
			this.queue = queue;
			this.remark = remark;
		}

		// 线程运行主体
		public void run() {
			while (true) {
				try {
					Thread.sleep(CommonUtil.randomInt(5, 1) * 1000); 
					ReqLog data = queue.popReqLog();// 添加日志
					if (data != null) {
						List list=new ArrayList<>();
						list.add(data);
						logger.debug("popReqLog " + data.getClientIp());
						commonService.batchInsert(list);	
					}
				} catch (Exception e) {
					logger.debug("writeLog  error:" + e);
				}
			}
		}
	}

}
